#include "unp.h"
#include "user.h"

void relay_message(struct user *u,int  *group_fds,int *group_ids,int *maxi,fd_set *set)
{
	char line[MAXLINE],tip[MAXLINE];
	ssize_t	n;
	int i;
	int num;
	void inform(struct user *u,int *group_fds,int *group_ids,int *maxi,fd_set *set,int flag);
	
	num = *maxi+1;

	if((n=Readline(u->socket,line,MAXLINE))==0)
	{
		printf("Client %d is out\n",u->socket);
		inform(u,group_fds,group_ids,maxi,set,-1);
		close(u->socket);
		FD_CLR(u->socket,set);
		for (i=0;i<num;i++)
		{
			if(group_fds[i]==u->socket)
			{
				group_fds[i] = -1;
				break;
			}
		}
	}
	
	if(n<0)
	{
		err_sys("relay_message read error");
		return;
	}
	
			
	for(i=0;i<num;i++)
	{
		if(group_fds[i]!=-1 && group_fds[i]!=u->socket && group_ids[i]!=-1 && u->group_id == group_ids[i])
		{	
			printf("%d socket is saying to NO.%d socket %d,and %d in toltal \n",u->socket,i,group_fds[i],num);
			snprintf(tip,sizeof(tip),"%s :",u->name);
		
			if((writen(group_fds[i],tip,strlen(tip))<0) || ( writen(group_fds[i],line,n)<0 ))
			{
				fprintf(stderr,"Write error to fd%d,closing fd.\n",group_fds[i]);
				close(group_fds[i]);
				FD_CLR(group_fds[i],set);
				group_fds[i] = -1;
				
			}
	
		}
	}

}
